package net.mikoo.seals.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

/**
 * Http协议访问工具类
 * 
 */
public abstract class HttpUtil {

	/**
	 * 获取HttpClient对象(默认编码utf-8)
	 * 
	 * @return HttpClient对象
	 */
	private static HttpClient getHttpClient() {
		return getHttpClient("UTF-8");
	}

	/**
	 * 按encoding编码获取HttpClient对象
	 * 
	 * @param encoding
	 *            字符编码
	 * @return HttpClient对象
	 */
	private static HttpClient getHttpClient(String encoding) {
		HttpClient client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager());
		client.getParams().setContentCharset(encoding);
		client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
		client.getParams().setSoTimeout(10000);
		return client;
	}

	/**
	 * 按get方式提交url
	 * 
	 * @param url
	 *            需要访问的URL地址
	 * @return 访问url后返回的内容
	 */
	public static String get(String url) {
		GetMethod method = new GetMethod(url);
		try {
			int status = getHttpClient("UTF-8").executeMethod(method);
			if (status == 200) {
				return method.getResponseBodyAsString();
			}
		} catch (Exception e) {
			return null;
		} finally {
			method.releaseConnection();
		}
		return null;
	}

	/**
	 * 按get方式提交url
	 * 
	 * @param url
	 *            需要访问的URL地址
	 * @return 访问url后返回的内容
	 */
	public static String get(String url, String... headers) {
		if (headers.length % 2 != 0) {
			throw new IllegalArgumentException("Invalid number of parameters; each name must have a corresponding value!");
		}
		GetMethod method = new GetMethod(url);
		for (int i = 0; i < headers.length; i += 2) {
			if (headers[i] == null || headers[i + 1] == null)
				continue;
			method.addRequestHeader(headers[i], headers[i + 1]);
		}
		try {
			int status = getHttpClient("UTF-8").executeMethod(method);
			if (status == 200) {
				return method.getResponseBodyAsString();
			} else {
				return status + "";
			}
		} catch (Exception e) {
			return null;
		} finally {
			method.releaseConnection();
		}
	}

	/**
	 * 按post方式提交url
	 * 
	 * @param url
	 *            需要访问的URL地址
	 * @param params
	 *            提交参数
	 * @return 访问url后返回的内容
	 * @throws Exception
	 */
	public static String post(String url, String... params) {
		if (params.length % 2 != 0) {
			throw new IllegalArgumentException("Invalid number of parameters; each name must have a corresponding value!");
		}
		PostMethod method = new PostMethod(url);
		method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;application/json;charset=UTF-8");
		for (int i = 0; i < params.length; i += 2) {
			if (params[i] == null || params[i + 1] == null)
				continue;
			method.addParameter(params[i], params[i + 1]);
			method.addRequestHeader(params[i], params[i + 1]);
		}
		try {
			int status = getHttpClient().executeMethod(method);
			return method.getResponseBodyAsString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			method.releaseConnection();
		}
	}

	/**
	 * 按post方式提交url
	 * 
	 * @param url
	 *            需要访问的URL地址
	 * @param params
	 *            提交参数
	 * @return 访问url后返回的内容
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	public static String post(String url, String params) {

		PostMethod method = new PostMethod(url);
		try {
			method.addRequestHeader("Content-Type", "application/json;charset=utf-8"); 
			method.setRequestBody(params);
			int status = getHttpClient().executeMethod(method);
			if (status == 200) {
				return method.getResponseBodyAsString();
			} else {
				return status + "";
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}
		return null;
	}
	
	public static String post1(String url, String params) {

		PostMethod method = new PostMethod(url);
		try {
			method.addRequestHeader("Content-Type", "text/html;charset=utf-8"); 
			method.setRequestBody(params);
			int status = getHttpClient().executeMethod(method);
			if (status == 200) {
				return method.getResponseBodyAsString();
			} else {
				return status + "";
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}
		return null;
	}

	public static String upload(String url, File file, String... params) throws Exception {
		if (params.length % 2 != 0) {
			throw new IllegalArgumentException("Invalid number of parameters; each name must have a corresponding value!");
		}
		for (int i = 0; i < params.length; i += 2) {
			if (params[i] == null || params[i + 1] == null)
				continue;
			if (i == 0) {
				url = url.concat("?");
			}
			url = url.concat(params[i].toString()).concat("=").concat(params[i + 1].toString()).concat("&");
		}
		PostMethod method = new PostMethod(url);
		method.setRequestHeader("Connection", "Keep-Alive");
		method.setRequestHeader("Cache-Control", "no-cache");
		try {
			FilePart media = new FilePart("media", file);
			Part[] parts = new Part[] { media };
			MultipartRequestEntity entity = new MultipartRequestEntity(parts, method.getParams());
			method.setRequestEntity(entity);
			int status = getHttpClient().executeMethod(method);
			if (status == HttpStatus.SC_OK) {
				return method.getResponseBodyAsString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void download(String url, String path) {
		GetMethod method = new GetMethod(url);
		try {
			getHttpClient().executeMethod(method);
			InputStream in = method.getResponseBodyAsStream();
			FileOutputStream out = new FileOutputStream(new File(path));
			byte[] b = new byte[1024];
			int len = 0;
			while ((len = in.read(b)) != -1) {
				out.write(b, 0, len);
			}
			in.close();
			out.close();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}
	}

	/**
	 * post请求
	 * 
	 * @param url
	 *            url地址
	 * @param jsonParam
	 *            参数
	 * @return
	 */
	public static JSONObject httpPost(String url, JSONObject jsonParam) {
		// post请求返回结果
		DefaultHttpClient httpClient = new DefaultHttpClient();
		JSONObject jsonResult = null;
		HttpPost method = new HttpPost(url);
		try {
			if (null != jsonParam) {

				List<BasicNameValuePair> formParams = new ArrayList<BasicNameValuePair>();

				// 对传入的参数进行排序
				LinkedHashMap<String, String> jsonMap = JSON.parseObject(jsonParam.toJSONString(), new TypeReference<LinkedHashMap<String, String>>() {
				});

				// 组装formParams
				for (Map.Entry<String, String> entry : jsonMap.entrySet()) {
					BasicNameValuePair e = new BasicNameValuePair(entry.getKey(), entry.getValue());
					formParams.add(e);
				}

				HttpEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");

				method.setEntity(entity);
			}
			HttpResponse result = httpClient.execute(method);
			url = URLDecoder.decode(url, "UTF-8");

			// 请求发送成功，并得到响应
			if (result.getStatusLine().getStatusCode() == 200) {
				String str = "";
				try {
					// 读取服务器返回过来的json字符串数据
					str = EntityUtils.toString(result.getEntity());

					// 把json字符串转换成json对象
					jsonResult = JSONObject.parseObject(str);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return jsonResult;
	}

	/**
	 * 发送get请求
	 * 
	 * @param url
	 *            路径
	 * @return
	 */
	public static JSONObject httpGet(String url) {
		// get请求返回结果
		JSONObject jsonResult = null;
		try {
			DefaultHttpClient client = new DefaultHttpClient();
			// 发送get请求
			HttpGet request = new HttpGet(url);
			HttpResponse response = client.execute(request);

			// 请求发送成功，并得到响应
			if (response.getStatusLine().getStatusCode() == 200) {
				// 读取服务器返回过来的json字符串数据
				String strResult = EntityUtils.toString(response.getEntity());
				// 把json字符串转换成json对象
				jsonResult = JSONObject.parseObject(strResult);
				url = URLDecoder.decode(url, "UTF-8");
			} else {
				// 请求失败

			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return jsonResult;
	}
}
